package com.laycoding.layrpc.handler.client;


import com.laycoding.layrpc.common.LayRpcRegistryCache;
import com.laycoding.layrpc.common.LayRpcRegistyCache;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.logging.log4j.Logger;
import org.apache.zookeeper.data.Stat;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalTime;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class RpcCommandLine implements CommandLineRunner {
    @Value("${layrpc.path}")
    private String path;
    @Autowired
    private CuratorFramework curatorFramework;

    ConcurrentHashMap<String, Object> serviceMap = LayRpcRegistyCache.serviceMap;

    @Autowired
    LayRpcClientRegistry layRpcClientRegistry;

    @Override
    public void run(String... args) throws Exception {
        Stat stat = curatorFramework.checkExists().forPath(path);
        if (stat != null) {
            List<String> strings = curatorFramework.getChildren().forPath(path);
            for (String string : strings) {
                String dataPath = path + "/" + string;
                byte[] bytes = curatorFramework.getData().forPath(dataPath);
                String s = new String(bytes);
                serviceMap.put(string, s);
            }
        }
        doListener(curatorFramework);
        doRegistry();
    }

    public void doRegistry(){
        String rpcservice = LayRpcRegistyCache.getLoadBlance("rpcservice");
        // String rpcservice = ZkServiceCache.getLoadBlance("rpcservice");
        if (StringUtils.isEmpty(rpcservice)){
           // return "服务不可用";
            return;
        }
        String[] split = rpcservice.split(":");
        layRpcClientRegistry.setHost(split[0]);
        layRpcClientRegistry.setPort(Integer.valueOf(split[1]));
        layRpcClientRegistry.connect();

        System.out.println("success ");
    }

    public void doListener(CuratorFramework curatorFramework) throws Exception {
        PathChildrenCache cache = new PathChildrenCache(curatorFramework, path, true);
        cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        cache.rebuild();
        cache.getListenable().addListener((curatorFramework1, pathChildrenCacheEvent) -> {
            String name = "", path = "";
            switch (pathChildrenCacheEvent.getType()) {
                case CHILD_ADDED:
                    ChildData childData = pathChildrenCacheEvent.getData();
                    path = childData.getPath();
                    byte[] data = childData.getData();
                    name = new String(data);
                    String[] arr = path.split("/");
                    serviceMap.put(arr[2], name);
                    log.info("Listener the Rpc service is add ...");
                    doRegistry();
                    break;
                case CHILD_REMOVED:
                    ChildData childData1 = pathChildrenCacheEvent.getData();
                    path = childData1.getPath();
                    String[] arr1 = path.split("/");
                    serviceMap.remove(arr1[2]);
                    log.info("Listener the Rpc service is deleted ...");
                    break;
                case CHILD_UPDATED:
                    break;
                default:
                    break;
            }
        });
    }
}
